<template>
  <el-container v-loading="loading">

    <!--<el-row>
      <el-form label-width="100px" label-position="left" size="small">
        <el-form-item label="顾客等级筛选">
          <el-radio-group v-model="constraintForm.member_grade" fill="#1AB394">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button :label="userLevelItem.level" v-for="userLevelItem in userLevelGroup">{{userLevelItem.name}}</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="筛选">
          <el-radio-group v-model="constraintForm.order_type" fill="#1AB394">
            <el-radio-button label="0">不限</el-radio-button>
            <el-radio-button label="1" >近30天成交的客户</el-radio-button>
            <el-radio-button label="2">近30未下单的客户</el-radio-button>
            <el-radio-button label="3">近30天取消订单的客户</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="时间">
          <el-radio-group v-model="constraintForm.timeType" fill="#1AB394" @change="getTimed">
            <el-radio-button label="1">不限</el-radio-button>
            <el-radio-button label="2">近一周</el-radio-button>
            <el-radio-button label="3">近一月</el-radio-button>
            <el-radio-button label="4">近三月</el-radio-button>
            <el-radio-button label="5">自定义</el-radio-button>
          </el-radio-group>

          <el-date-picker
            class="el-date-picker"
            v-model="constraintForm.time"
            type="datetimerange"
            value-format="timestamp"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
            v-if="constraintForm.timeType == '5'">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="其他">
          <el-autocomplete
            v-model="constraintForm.text"
            :fetch-suggestions="querySearchAsync"
            placeholder="请选择配送人员"
            @select="handleSelect"
            clearable>
            <template slot-scope="{ item }">
              <div>{{ item.nickname }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>


        <el-form-item>
          <el-button type="success" @click="constraintSearchData">筛选</el-button>
        </el-form-item>
      </el-form>
    </el-row>-->

    <el-row>
      <el-button
        icon="fa fa-fw fa-refresh"
        size="mini"
        type="info"
        @click="handleRefresh">
      </el-button>
			<el-input placeholder="请输入手机号码或微信昵称" v-model="card_no" style="width: 300px;" />
			<el-button type="primary" icon="el-icon-search" @click="seach_btn">搜索</el-button>
			<div style="float: right;margin-right: 20px;">
				<el-date-picker
					v-model="value6"
					type="daterange"
					range-separator="至"
					start-placeholder="开始日期"
					end-placeholder="结束日期"
					value-format="yyyy-MM-dd"
					@change='download_btn'>
				</el-date-picker>
				<el-button type="primary"><a :href="url+'/index.php?s=home/excel/user&time_area='+times"  target="_blank" style='color: #fff;'>导出数据</a></el-button>
			</div>
    </el-row>

    <el-table
      @selection-change="handleSelectionChange"
      :data="tableData"
      tooltip-effect="dark"
      border
      :default-sort="{prop: 'date', order: 'descending'}"
      :row-class-name="tableRowClassName">
      <el-table-column
        prop="nickname"
        label="微信昵称"
        width="200">
      </el-table-column>

      <el-table-column
        prop="avatar_url"
        label="头像"
        show-overflow-tooltip>
        <template slot-scope="scope">
          <img :src="scope.row.avatar_url" class="logo-img">
        </template>
      </el-table-column>

      <el-table-column
        prop="sex"
        label="性别"
        sortable
        width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sex==0">女</el-tag>
          <el-tag v-if="scope.row.sex==1">男</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="is_online"
        label="是否在线"
        sortable
        width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.is_online==0">离线</el-tag>
          <el-tag v-if="scope.row.is_online==1">在线</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="phone"
        label="手机号"
        width="150">
      </el-table-column>

      <el-table-column
        prop="price"
        label="余额">
        <template slot-scope="scope">
          <i class="fa fa-fw fa-rmb"></i>
          <span style="margin-left: 10px">{{ scope.row.price }}</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="create_time"
        label="创建时间"
        sortable>
        <template slot-scope="scope">
          <i class="fa fa-fw fa-clock-o"></i>
          <span style="margin-left: 10px">{{ scope.row.create_time }}</span>
        </template>
      </el-table-column>
			
			<el-table-column
			    fixed="right"
			    width="250"
			    label="操作">
			    <template slot-scope="scope">
			      <el-button
			        size="mini"
			        type="primary"
			        title="用户充值"
			        @click="handleUserRecharge(scope.$index, scope.row)">
			        用户充值
			      </el-button>
			
			      <el-button
			        size="mini"
			        title="用户历史充值记录"
			        @click="handleUserRechargeHistory(scope.$index, scope.row)">
			        用户历史充值记录
			      </el-button>
			    </template>
			  </el-table-column>
			
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.currentPage"
      :page-sizes="pagination.pageSizes"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

		 <!-- 用户充值 -->
    <el-dialog
      title="用户充值"
      :visible.sync="userRechangeDialogVisible"
      width="30%"
      >
      <div>
        <div class="m-b-15">
          <div class="m-b-15" style="margin-bottom: 10px;">
            <el-input size="small" placeholder="请输入内容" v-model="userRechangeInfo.price">
              <template slot="prepend">充值金额</template>
            </el-input>
          </div>
          <el-input size="small" placeholder="请输入内容" v-model="userRechangeInfo.mark">
            <template slot="prepend">备注信息</template>
          </el-input>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="userRechangeDialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="sendUserRechangeRequestHandler">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog width="90%" title="充值记录" :visible.sync="historyDialogVisible">
      <el-table :data="historyData">
        <el-table-column prop="money" label="充值金额" width="200" >
          <template slot-scope="scope">
            <i class="fa fa-fw fa-rmb"></i>
            <span style="margin-left: 10px">{{ scope.row.money }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="after_money" label="充值后金额" width="200">
          <template slot-scope="scope">
            <i class="fa fa-fw fa-rmb"></i>
            <span style="margin-left: 10px">{{ scope.row.money }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="mark" label="充值原因"></el-table-column>
        <el-table-column prop="admin" label="充值人" width="200"></el-table-column>
        <el-table-column prop="create_time" label="充值时间" width="200">
          <template slot-scope="scope">
            <i class="fa fa-fw fa-clock-o"></i>
            <span style="margin-left: 10px">{{ scope.row.create_time }}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleHistorySizeChange"
        @current-change="handleHistoryCurrentChange"
        :current-page="historyPagination.currentPage"
        :page-sizes="historyPagination.pageSizes"
        :page-size="historyPagination.pageSize"
        :total="historyPagination.total"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </el-dialog>

  </el-container>
</template>

<script>
	import api from '@/fetch/api.js'
  export default {
    mounted: function () {
      // this.getUserLevel();
			
      this.getData();
    },
    methods: {
			/**
       * 用户充值
       * @param index
       * @param row
       */
      handleUserRecharge(index, row) {
        let _this = this;
        let _id = row.id;
        // 初始化信息
        _this.userRechangeDialogVisible = true;
        _this.userRechangeInfo.price = '';
        _this.userRechangeInfo.mark = '';
        _this.userRechangeInfo.userId = _id;
      },
			 sendUserRechangeRequestHandler: function () {
        let _this = this;
        if (_this.userRechangeInfo.price == '') {
          this.$message({
            type: 'warning',
            message: '请填写充值金额'
          });
          return false;
        }
        if (_this.userRechangeInfo.mark == '') {
          this.$message({
            type: 'warning',
            message: '请填写充值备注信息'
          });
          return false;
        }
        this.api.userRecharge({
          uid: _this.userRechangeInfo.userId,
          price: _this.userRechangeInfo.price,
          mark: _this.userRechangeInfo.mark
        }).then(function (res) {
          if (res.code == 1) {
            _this.getData();
            _this.userRechangeDialogVisible = false;
            _this.$message({
              showClose: true,
              message: res.msg,
              type: 'success'
            });
          } else {
            _this.$message({
              showClose: true,
              message: res.msg,
              type: 'warning'
            });
          }
        }).catch(function (error) {
          throw new Error(error);
        });
      },
			 /**
       * 用户充值历史记录
       * @param index
       * @param row
       */
      handleUserRechargeHistory(index, row) {
        let _this = this;
        let _id = row.id;
        // 初始化信息
        _this.historyDialogVisible = true;
        _this.userRechangeInfo.userId = _id;
        _this.getHistoryData();
      },
			 /**
       * 历史记录分页数改变
       */
      handleHistorySizeChange: function (pageSize) {
        this.historyPagination.pageSize = pageSize;
        this.getHistoryData();
      },
      /**
       * 历史记录当前页面改变
       * @param currentPage
       */
      handleHistoryCurrentChange: function (currentPage) {
        this.historyPagination.currentPage = currentPage;
        this.getHistoryData();
      },
			 /**
       * 数据请求
       * */
      getHistoryData: function () {
        let _this = this;
        this.api.getUserRechargeHistoryList({
          page: this.historyPagination.currentPage,
          paginate: this.historyPagination.pageSize,
          uid: _this.userRechangeInfo.userId
        }).then(function (res) {
          if (res.code == 1) {
            _this.historyData = res.data.data;
            _this.historyPagination.total = res.data.total;
          }
          _this.loading = false;
        }).catch(function (res) {
          throw new Error(res);
        });
      },
			 /**
			 * 搜索用户
			 * */
			 seach_btn(){
			 	if(!this.card_no){
			 		this.$message({
			 		  showClose: false,
			 		  message: '手机号码或微信昵称不能为空',
			 		  type: 'warning',
			 			duration:1000
			 		});
			 		return false;
			 	}
			 	this.pagination.currentPage= 1
			 	this.times=''
			 	this.getData();
			 },
			 
      /**
       * 数据请求
       * */
      getData: function () {
        let _this = this;
        this.api.getUserList({
          page: this.pagination.currentPage,
          rows: this.pagination.pageSize,
					time_area:this.times,
					nickname:this.card_no,
          // id: this.constraintForm.text != '' ? this.constraintForm.id : '',
          // order_type: this.constraintForm.order_type,
          // member_grade: this.constraintForm.member_grade,
          // create_time: this.constraintForm.time.length > 0 ? this.constraintForm.time[0] + '-' + this.constraintForm.time[1] : 0
        }).then(function (res) {
          if (res.code == 1) {
            _this.tableData = res.data.data;
            _this.pagination.total = res.data.total;
          }
          _this.loading = false;
        }).catch(function (res) {
          throw new Error(res);
        });
      },
      /**
       * 用户等级加载
       * */
      getUserLevel: function () {
        let _this = this;
        this.api.getUserLevelList().then(function (res) {
          if (res.code == 1) {
            _this.userLevelGroup = res.data.data;
          }
        }).catch(function (res) {
          throw new Error(res);
        });
      },
      /**
       * 分页数改变
       */
      handleSizeChange: function (pageSize) {
        this.pagination.pageSize = pageSize;
        this.getData();
      },
      /**
       * 当前页面改变
       * @param currentPage
       */
      handleCurrentChange: function (currentPage) {
        this.pagination.currentPage = currentPage;
        this.getData();
      },
      tableRowClassName({row, rowIndex}) {
        if (rowIndex === 1) {
          return 'warning-row'
        } else if (rowIndex === 3) {
          return 'success-row'
        }
        return ''
      },
      /**
       * 编辑单个
       * */
      handleEditItem(index, row) {
        this.$router.push({
          name: 'AssociatorGradeEditor',
          params: {
            id: row.id,
            methodType: this.constant.EDITORMETHOD
          }
        })
      },
      /**
       * 数据刷新
       */
      handleRefresh: function () {
				this.value6=''
				this.pagination.currentPage= 1
				this.times=''
				this.card_no=''
				this.getData();
        this.$message({
          showClose: true,
          message: '刷新成功',
          type: 'success'
        });
      },
      /**
       * 表格选中状态记录
       * @param val
       */
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      /**
       * 获取时间
       * @param type
       */
      getTimed: function () {
        const start = new Date();
        const end = new Date();
        let day = 0;
        if (this.constraintForm.timeType == '2') {
          day = 7;
        } else if (this.constraintForm.timeType == '3') {
          day = 30;
        } else if (this.constraintForm.timeType == '4') {
          day = 90;
        }
        if (this.constraintForm.timeType == '2' || this.constraintForm.timeType == '3' || this.constraintForm.timeType == '4') {
          start.setTime(start.getTime() - 3600 * 1000 * 24 * day);
          let timeArr = [];
          timeArr.push(start.getTime());
          timeArr.push(end.getTime());
          this.constraintForm.time = timeArr;
        } else if (this.constraintForm.timeType == '1' || this.constraintForm.timeType == '5') {
          this.constraintForm.time = [];
        }
      },
      /**
       * 条件数据检索
       */
      constraintSearchData: function () {
        this.getData();
        this.$message({
          showClose: true,
          message: '查询成功',
          type: 'success'
        });
      },
      /**
       * 远程数据加载
       */
      querySearchAsync(queryString, cb) {
        let _this = this;
        this.api.searchUserByUserName({name: queryString}).then(function (res) {
          if(res.code == '1'){
            cb(res.data.data);
          }
        }).catch(function (res) {
          throw new Error(res);
        });
      },
      /**
       * 搜索下拉选择
       * @param item
       */
      handleSelect(item) {
        this.constraintForm.text = item.nickname;
        this.constraintForm.id = item.id;
      },
			download_btn(){
				if(!this.value6){
					this.pagination.currentPage=1
					this.times = ''
					this.card_no = ''
					this.getData();
				}else{
					let times=this.value6[0]+'~'+this.value6[1]
					this.pagination.currentPage=1
					this.times = times 
					this.card_no = ''
					this.getData();
				}
			}
    },
    data() {
      return {
				times:'',
				card_no:'',
				url:api.baseUrlPrefix,
				value6:'',
        loading: true,  // 页面加载
        tableData: [],
        userLevelGroup:[
          {                //类型：Object  必有字段  备注：无
            id:135,                //类型：Number  必有字段  备注：无
            level:0,                //类型：Number  必有字段  备注：等级
            name:"lv0"                //类型：String  必有字段  备注：等级名称
          },
          {                //类型：Object  必有字段  备注：无
            id:136,                //类型：Number  必有字段  备注：无
            level:1,                //类型：Number  必有字段  备注：无
            name:"lv1"                //类型：String  必有字段  备注：无
          },
          {                //类型：Object  必有字段  备注：无
            id:137,                //类型：Number  必有字段  备注：无
            level:2,                //类型：Number  必有字段  备注：无
            name:"lv2"                //类型：String  必有字段  备注：无
          },
          {                //类型：Object  必有字段  备注：无
            id:138,                //类型：Number  必有字段  备注：无
            level:3,                //类型：Number  必有字段  备注：无
            name:"lv3"                //类型：String  必有字段  备注：无
          },
          {                //类型：Object  必有字段  备注：无
            id:139,                //类型：Number  必有字段  备注：无
            level:4,                //类型：Number  必有字段  备注：无
            name:"lv4"                //类型：String  必有字段  备注：无
          },
          {                //类型：Object  必有字段  备注：无
            id:140,                //类型：Number  必有字段  备注：无
            level:5,                //类型：Number  必有字段  备注：无
            name:"lv5"                //类型：String  必有字段  备注：无
          },
          {                //类型：Object  必有字段  备注：无
            id:141,                //类型：Number  必有字段  备注：无
            level:6,                //类型：Number  必有字段  备注：无
            name:"lv6"                //类型：String  必有字段  备注：无
          }
        ],
        multipleSelection: [],
        pagination: {
          total: 5,
          currentPage: 1,
          pageSize: 10,
          pageSizes: [5, 10, 20, 25, 30, 50, 100],
        },
        constraintForm: {
          order_type: '0',    // 	1,近30天成交；2，近30天未下订单；3，近30天取消订单；默认0
          timeType: '1',   // 时间类型 1=>不限 2=>近一周 3=>近一月 4=>近三月 5=>自定义
          time: [],    // 时间戳，中横线分割‘-’,默认0
          text: '',    // 检索姓名，默认''
          id: '',    // 用户id，默认0
          member_grade: '',   // 等级名称 默认''
        },
				userRechangeDialogVisible: false,  // 充值对话框状态
        userRechangeInfo: {  // 充值信息
          userId: '', // 用户ID
          mark: '', // 充值愿意
          price: '' // 充值金额
        },
        historyDialogVisible: false,
        historyPagination: {
          total: 5,
          currentPage: 1,
          pageSize: 10,
          pageSizes: [5, 10, 20, 25, 30, 50, 100],
        },  // 历史分页
        historyData: [],  // 历史记录数据
      }
    },
  }
</script>

<style scoped>
  .el-container {
    display: block;
  }

  .el-table, .el-row{
    width: 98% !important;
    margin: 15px auto;
  }
  .el-pagination{
    text-align: center;
    margin: 15px 0;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }

  .logo-img{
    width: 40px;
    height: 40px;
  }

  .el-date-picker{
    top: -3px;
    margin: 0 0 0 15px;
  }
</style>
